package com.lottery.im.module.tim.ui;

import android.support.annotation.LayoutRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.module.tim.utils.TimFileUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

class FaceGridViewAdapter extends BaseAdapter {
  private List<String> dataList;

  @LayoutRes
  private int mLayout_res;

  FaceGridViewAdapter(List<String> datas, int page, int layout_res) {
    dataList = new ArrayList<>();
    mLayout_res = layout_res;
    //start end分别代表要显示的数组在总数据List中的开始和结束位置
    int start = page * ChatInput.item_grid_num;
    int end = start + ChatInput.item_grid_num;
    while ((start < datas.size()) && (start < end)) {
      dataList.add(datas.get(start));
      start++;
    }
  }

  @Override
  public int getCount() {
    return dataList.size();
  }

  @Override
  public Object getItem(int i) {
    return dataList.get(i);
  }

  @Override
  public long getItemId(int i) {
    return i;
  }

  @Override
  public View getView(int i, View itemView, ViewGroup viewGroup) {
    ViewHolder mHolder;
    if (itemView == null) {
      mHolder = new ViewHolder();
      itemView = LayoutInflater.from(viewGroup.getContext())
          .inflate(mLayout_res, viewGroup, false);
      mHolder.iv_img = (ImageView) itemView.findViewById(R.id.iv_face);
      itemView.setTag(mHolder);
    } else {
      mHolder = (ViewHolder) itemView.getTag();
    }
    String bean = dataList.get(i);

    if (bean.startsWith("emoticon")) {
      Glide.with(MyApplication.getInstance())
          .load("file:///android_asset/emoticon/" + bean.substring("emoticon".length(),
              bean.length()))
          .into(mHolder.iv_img);
    } else if (bean.startsWith("lt")) {
      Glide.with(MyApplication.getInstance())
          .load("file:///android_asset/lt/" + bean)
          .into(mHolder.iv_img);
    } else if (bean.startsWith("sx")) {
      Glide.with(MyApplication.getInstance())
          .load("file:///android_asset/sx/" + bean)
          .into(mHolder.iv_img);
    } else if (bean.startsWith("xxy")) {
      Glide.with(MyApplication.getInstance())
          .load("file:///android_asset/xxy/" + bean)
          .into(mHolder.iv_img);
    } else {
      if (TimFileUtil.isCacheFileExist(bean + ".jpg")) {
        Glide.with(MyApplication.getInstance())
            .load(new File(TimFileUtil.getCacheFilePath(bean + ".jpg")))
            .into(mHolder.iv_img);
      }
    }

    return itemView;
  }

  private class ViewHolder {
    private ImageView iv_img;
  }
}